import WebGl from '@/modules/three';
// import fontJson from 'three/examples/fonts/helvetiker_regular.typeface.json'
const fontJson = require('three/examples/fonts/helvetiker_regular.typeface.json');

const { Three, TWEEN, dat, Stats } = WebGl;

class WebGlControl {
  private container: any;
  private camera: any;
  private scene: any;
  private renderer: any;
  private stats: any;
  private animateFrame: any;
  private starsGroup: any; //

  private Geometrys: {
    cubeGeometry?: any;
    starsGeometry?: any;
  } = {}; //保存所有Geometry，方便统一销毁
  private Materials: {
    cubeMaterial?: any;
    starsMaterial?: any;
  } = {}; //保存所有Material，方便统一销毁

  private GuiInit: any = null;
  private guiData: any = {
    color: '#ffffff',
    mouseMove: false,
    autoRotate: false,
    SEPARATION: 100,
    AMOUNTX: 50,
    AMOUNTY: 50,
    positionYBase: 50, //粒子y晃动幅度
  };
  private mouseData: any = {
    mouseX: 0,
    mouseY: 0,
  };

  public init = () => {
    // if(this.scene) {return}
    this.container = document.getElementById('WebGL-wave-points-test');
    let width = this.container.clientWidth,
      height = this.container.clientHeight;

    this.scene = new Three.Scene();

    this.camera = new Three.PerspectiveCamera(60, width / height, 1, 10000);
    this.camera.position.set(944, 206, 262);
    this.camera.lookAt(this.scene.position);

    this.renderer = new Three.WebGLRenderer();
    // this.renderer.setClearColor( 0xffffff );
    this.renderer.setPixelRatio(window.devicePixelRatio);
    this.renderer.setSize(width, height);
    this.container.appendChild(this.renderer.domElement);

    this.addThings();
    this.addLight(); //+光源
    this.animate(); //开始动
    this.initEventListen();
    this.initStats();

    this.initGui();
  };
  public destroy = () => {
    this.toggleGui(0);
    Object.values(this.Geometrys).forEach((e) => {
      e.dispose();
    });
    Object.values(this.Materials).forEach((e) => {
      e.dispose();
    });
    this.scene.clear();
    this.renderer.dispose();
    this.renderer.forceContextLoss();
    this.camera = null;
    this.scene = null;
    this.renderer = null;
    this.GuiInit = null;
    cancelAnimationFrame(this.animateFrame);
  };

  public initGui = () => {
    if (this.GuiInit) {
      this.toggleGui();
      return;
    }
    this.GuiInit = new dat.GUI({
      // autoPlace: false
    });

    this.GuiInit.domElement.style.position = 'absolute';
    this.GuiInit.domElement.style.right = '10px';
    this.GuiInit.domElement.style.top = '10px';

    let GuiController = this.GuiInit.addFolder('控制窗口');
    GuiController.addColor(this.guiData, 'color').name('粒子颜色');
    GuiController.add(this.guiData, 'mouseMove').name('鼠标晃动');
    GuiController.open();

    let starsGui = this.GuiInit.addFolder('stars position');
    starsGui.add(this.starsGroup.position, 'x', -500, 500, 1);
    starsGui.add(this.starsGroup.position, 'y', -500, 500, 1);
    starsGui.add(this.starsGroup.position, 'z', -500, 500, 1);
    starsGui.open();

    let starsGuiRotate = this.GuiInit.addFolder('stars rotation');
    starsGuiRotate.add(this.guiData, 'autoRotate').name('自动旋转');
    starsGuiRotate.add(this.starsGroup.rotation, 'x', -3.14, 3.14, 0.01);
    starsGuiRotate.add(this.starsGroup.rotation, 'y', -3.14, 3.14, 0.01);
    starsGuiRotate.add(this.starsGroup.rotation, 'z', -3.14, 3.14, 0.01);
    //rotation是欧拉类型的值，单位是π；比如让物体按Y轴正方向旋转45°可以写成 object3D.rotation.y+=0.25*Math.PI
    starsGuiRotate.open();

    let otherGui = this.GuiInit.addFolder('其他');
    otherGui.add(this.guiData, 'positionYBase', 20, 100, 1).name('晃动幅度');
    otherGui.open();
  };
  private initStats = () => {
    this.stats = new Stats();
    this.stats.showPanel(0); // 0: fps, 1: ms, 2: mb, 3+: custom
    this.stats.dom.style.position = 'absolute';
    this.container.appendChild(this.stats.dom);
  };

  public toggleGui = (state: any = null) => {
    if (!this.GuiInit || !this.GuiInit.domElement) {
      return;
    }
    let display = this.GuiInit.domElement.style.display == 'none' ? '' : 'none';
    if (state == 0) {
      display = 'none';
    }
    this.GuiInit.domElement.style.display = display;
  };

  private initEventListen = () => {
    this.container.addEventListener('pointermove', this.onPointerMove);
  };
  private onPointerMove = (event) => {
    if (event.isPrimary === false) return;
    this.mouseData.mouseX = event.clientX - this.container.clientWidth;
    this.mouseData.mouseY = event.clientY - this.container.clientHeight;
  };

  private addLight = () => {
    // let ambi = new Three.AmbientLight(0x686868);
    // this.scene.add(ambi);
    // let spotLight = new Three.DirectionalLight(0xffffff);
    // spotLight.position.set(550, 100, 550);
    // spotLight.intensity = 0.6;
    // this.scene.add(spotLight);
    // let light = new Three.PointLight( 0xFFFF00 );
    // light.position.set( -100, 100, 0 );
    // this.scene.add(light);
  };

  private addThings = () => {
    const axesHelper = new Three.AxesHelper(800);
    this.scene.add(axesHelper); //添加坐标轴；红线是X轴，绿线是Y轴，蓝线是Z轴

    /** 立方体 **/
    // this.Geometrys.cubeGeometry = new Three.BoxGeometry( 100, 100, 100);
    // this.Materials.cubeMaterial = new Three.MeshLambertMaterial( { color: 0xfd59d7 } );
    // const cube = new Three.Mesh( this.Geometrys.cubeGeometry, this.Materials.cubeMaterial );
    // this.scene.add( cube );
    /** 立方体 **/

    /** 粒子 **/
    this.starsGroup = new Three.Group();
    this.scene.add(this.starsGroup);
    this.Geometrys.starsGeometry = new Three.BufferGeometry();
    let starPositionArr: any[] = [];
    let starSizeArr: any[] = [];

    for (let ix = 0; ix < this.guiData.AMOUNTX; ix++) {
      for (let iy = 0; iy < this.guiData.AMOUNTY; iy++) {
        const x =
          ix * this.guiData.SEPARATION -
          (this.guiData.AMOUNTX * this.guiData.SEPARATION) / 2; // x
        const y = 0;
        const z =
          iy * this.guiData.SEPARATION -
          (this.guiData.AMOUNTY * this.guiData.SEPARATION) / 2; // z
        starPositionArr.push(x, y, z);
        starSizeArr.push(100);
      }
    }
    this.Geometrys.starsGeometry.setAttribute(
      'position',
      new Three.Float32BufferAttribute(starPositionArr, 3),
    );
    // this.Materials.starsMaterial = new Three.MeshBasicMaterial({color: this.guiData.color})
    this.Materials.starsMaterial = new Three.PointsMaterial({
      color: this.guiData.color,
      size: 4,
    });
    const stars = new Three.Points(
      this.Geometrys.starsGeometry,
      this.Materials.starsMaterial,
    );
    this.starsGroup.add(stars);

    // this.Materials.starsMaterial.size = 20
    console.log('stars:', stars, this.Geometrys, this.Materials);
    /** 粒子 **/

    this.initTween();
  };

  private initTween = () => {
    // cameray: 20, z: 500
    // var tween = new TWEEN.Tween(this.starsGroup.position).to({y: 12, z: 300}, 1000).start()
    // tween.easing(TWEEN.Easing.Circular.Out);
  };

  private animate = () => {
    // if(!this.renderer){return;}
    if (this.stats) {
      this.stats.begin();
    }

    this.render();
    TWEEN.update();

    if (this.stats) {
      this.stats.end();
    }
    this.animateFrame = requestAnimationFrame(this.animate);
  };

  private starPositionCount = 0;
  private render = () => {
    // this.renderer.setClearColor(this.guiData.color,1.0);
    if (this.guiData.autoRotate) {
      // this.starsGroup.rotation.x+= 0.025
      this.starsGroup.rotation.y += 0.005;
    }

    if (this.guiData.mouseMove) {
      this.camera.position.x +=
        (-this.mouseData.mouseX - this.camera.position.x) * 0.015;
      this.camera.position.y +=
        (-this.mouseData.mouseY - this.camera.position.y) * 0.015;
    }

    /** 更新star位置 **/
    let starPositionArr: any[] =
      this.Geometrys.starsGeometry.attributes.position.array;
    // let starSizesArr:any[] = this.Geometrys.starsGeometry.attributes.size.array
    let starSizesArr: any[] = [];
    let ind = 0;

    for (let ix = 0; ix < this.guiData.AMOUNTX; ix++) {
      for (let iy = 0; iy < this.guiData.AMOUNTY; iy++) {
        const y =
          Math.sin((ix + this.starPositionCount) * 0.3) *
            this.guiData.positionYBase +
          Math.sin((iy + this.starPositionCount) * 0.5) *
            this.guiData.positionYBase;
        starPositionArr[ind + 1] = y; //要改的y的index 是1,4,7(ind+1)
        let size =
          (Math.sin((ix + this.starPositionCount) * 0.3) + 1.3) * 8 +
          (Math.sin((iy + this.starPositionCount) * 0.5) + 1.3) * 4;
        starSizesArr[ind / 3] = size;
        ind += 3;
      }
    }
    this.Geometrys.starsGeometry.setAttribute(
      'position',
      new Three.Float32BufferAttribute(starPositionArr, 3),
    );
    this.starPositionCount += 0.1;
    /** 更新star位置 **/
    this.Materials.starsMaterial.size = starSizesArr[0];
    // this.Materials.starsMaterial.setValue({})
    // this.Geometrys.starsGeometry.attributes.size.needsUpdate = true
    // this.Materials.starsMaterial.setValues({size: starSizesArr})

    /** 更新颜色 **/
    this.Materials.starsMaterial.setValues({ color: this.guiData.color });
    /** 更新颜色 **/

    this.renderer.render(this.scene, this.camera);
  };
}

const webGlControl = new WebGlControl();
export default webGlControl;
